package com.abc.tool;

import com.abc.bean.Case;
import com.abc.bean.Person;
import com.abc.bean.Photo;
import com.abc.bean.Text;
import com.abc.db.DBManager;
import com.abc.easyclaim.MainApplication;

import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.widget.TextView;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xmlpull.v1.XmlSerializer;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.xml.transform.OutputKeys;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.dom.DOMSource;
public class XmlUtil {
	public static void generateXmlFile(Integer caseId){
		DBManager mgr = MainApplication.getMgr();
		Case caze = mgr.queryCase(caseId);
		List<Text> texts = mgr.queryTexts(caseId);
		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                      .newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory
                      .newDocumentBuilder();
            Document document = documentBuilder.newDocument();

            Element rootElement = document.createElement("project");
            document.appendChild(rootElement);

            Element caseElement = document.createElement("case");
            caseElement.setAttribute("id", caze.getId().toString());
            caseElement.setAttribute("name", caze.getName());
            caseElement.setAttribute("accidentDate", caze.getAccidentDate());
            caseElement.setAttribute("accidentAddress", caze.getAccidentAddress());
            caseElement.setAttribute("lastModifyDate", caze.getLastModifyDate());
            caseElement.setAttribute("carNumber", caze.getCarNumber());
            caseElement.setAttribute("carOwnerName", caze.getCarOwnerName());
            caseElement.setAttribute("carOwnerPhone", caze.getCarOwnerPhone());
            caseElement.setAttribute("carOwnerAddr", caze.getCarOwnerAddr());
            caseElement.setAttribute("insuranceNumber", caze.getInsuranceNumber());
            caseElement.setAttribute("note", caze.getNote());
            caseElement.setAttribute("officerName", caze.getOfficerName());
            caseElement.setAttribute("officerNumber", caze.getOfficerNumber());
            caseElement.setAttribute("important",caze.getImportant());
            caseElement.setAttribute("location",caze.getLocation());
            caseElement.setAttribute("carBrand",caze.getCarBrand());
            rootElement.appendChild(caseElement);
            
            for (int i = 0; i < texts.size(); i++) {
            	Text text = texts.get(i);
            	Element textElement = document.createElement("text");
                rootElement.appendChild(textElement);
                textElement.setAttribute("id", text.getId().toString());
                textElement.setAttribute("title", text.getTitle());
                textElement.setAttribute("content", text.getContent());
                textElement.setAttribute("lastModifyDate", text.getLastModifyDate());
                textElement.setAttribute("caseId", text.getCaseId().toString());
			}


            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            Properties outFormat = new Properties();
            outFormat.setProperty(OutputKeys.INDENT, "yes");
            outFormat.setProperty(OutputKeys.METHOD, "xml");
            outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            outFormat.setProperty(OutputKeys.VERSION, "1.0");
            outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperties(outFormat);
            DOMSource domSource = 
            new DOMSource(document.getDocumentElement());
            OutputStream output = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(output);
            transformer.transform(domSource, result);
            String xmlString = output.toString();  
            FileWriter fw = null;         
            try {
				fw = new FileWriter(MainApplication.getSdPath()+"/easyclaim/tmp/"+caze.getName()+".xml");
				fw.write(xmlString);
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 


        } catch (ParserConfigurationException e) {
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }
	}
	
	public static void pullCreateXml() throws IllegalArgumentException, IllegalStateException, IOException{  
        //要存储的数据  
        Person person1=new Person(1, "Lucy", 15);  
        Person person2=new Person(2, "Tim", 20);  
        List<Person> persons=new ArrayList<Person>();  
        persons.add(person1);  
        persons.add(person2);  
          
        //要存储的xml文件的位置  
       // OutputStream outputStream=MainApplication.getContext().openFileOutput(MainApplication.getSdPath()+"/aa.xml", MainApplication.getContext().MODE_PRIVATE);
        FileOutputStream outputStream = new FileOutputStream(MainApplication.getSdPath()+"/"+"aa"+".txt",true);  
        //使用Xml工具类，获得serializer对象,pull解析器和生成器可以用Xml工具类直接获得，也可以像下面那样获得  
        //XmlPullParserFactory.newInstance().newPullParser();  
//      XmlPullParserFactory.newInstance().newSerializer();  
        XmlSerializer serializer=Xml.newSerializer();  
        serializer.setOutput(outputStream, "UTF-8");  
          
        serializer.startDocument("UTF-8", true);//开始文档  
          
        serializer.startTag(null, "persons"); //开始根节点persons  
        for(Person p:persons){  
            serializer.startTag(null, "person");//开始person节点  
              
            serializer.attribute(null, "id", p.getId()+"");//person节点的属性  
              
            serializer.startTag(null, "name");//开始name节点  
            serializer.text(p.getName());//name的文本节点  
            serializer.endTag(null, "name");//结束name节点  
              
            serializer.startTag(null, "age");//开始age节点  
            serializer.text(p.getAge()+"");//age的文本节点  
            serializer.endTag(null, "age");//结束age节点  
              
            serializer.endTag(null, "person");//结束person节点  
        }  
          
        serializer.endTag(null, "persons");//结束根节点persons  
          
        serializer.endDocument();//结束文档  
          
    } 
	
}
